//
//  ZXSampleStarAppraiseView.m
//  ZXStarAppraiseViewDemo
//
//  Created by LIUKUN-PC on 16/7/11.
//  Copyright © 2016年 liukun. All rights reserved.
//

#import "ZXSampleStarAppraiseView.h"

@interface ZXSampleStarAppraiseView ()

@property (nonatomic, strong) NSMutableArray<UIImageView *> *starImageViewArray;

@end

@implementation ZXSampleStarAppraiseView

- (void)layoutSubviews {
    CGFloat height = self.frame.size.height;
    CGFloat width = self.frame.size.width;
    
    CGFloat lenght = MIN(width / 5, height);
    
    for (int i = 0; i < self.starImageViewArray.count; i++) {
        self.starImageViewArray[i].frame = CGRectMake((width/5-lenght)/2+1 + i * width / 5, (height-lenght)/2, lenght - 2, lenght - 2);
    }
}

#pragma mark - OverWrite Init Methods

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)init {
    if (self = [super init]) {
        [self initSubViews];
    }
    return self;
}

- (void)initSubViews {
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    self.starImageViewArray = [NSMutableArray<UIImageView *> array];
    for (NSInteger i = 0; i < 5; i++) {
        UIImageView *starImageView = [[UIImageView alloc] init];
        [self.starImageViewArray addObject:starImageView];
        [self addSubview:starImageView];
    }

}


#pragma mark - Getter & Setter

- (void)setScore:(double)score {
    _score = score;
    if (_score > 5) {
        _score = 5;
    } else if (_score < 0){
        _score = 0;
    }
    //double精确性
    for (int i = 0; i < 6; i++) {
        if (ABS(_score - i) < 0.000001) {
            _score = i;
            break;
        }
    }
    
    
    int floorScore = floor(_score);
    int ceilScore = ceil(_score);
    
    for (NSInteger i = 0; i < 5; i++) {
        
        if (i + 1 <= floorScore) {
            self.starImageViewArray[i].image = [UIImage imageNamed:@"star_full_new"];
        } else if (i + 1 <= ceilScore && i + 1 > floorScore) {
            self.starImageViewArray[i].image = [UIImage imageNamed:@"star_half_new"];
        } else if (i + 1 > ceilScore) {
            self.starImageViewArray[i].image = [UIImage imageNamed:@"star_empty_new"];
        }
    }
}


@end
